package com.yang.util.tool;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: TODO
 * @Author: YangTing
 * @Date: 2024-05-07 08:37
 */

public class encoding {

    @Test
    public void test(){
        File file = new File("hello.txt");
//        FileInputStream
//        detectEncodingByByteOrderMark()
//        InputStream inputStream = new InputStream() {
//            @Override
//            public int read() throws IOException {
//                return 0;
//            }
//        }
//        detectEncodingByByteOrderMark();
    }

    public static String detectEncodingByByteOrderMark(InputStream input) throws IOException {
        byte[] bytes = new byte[4];
        if (-1 == input.read(bytes)) {
            return null;
        }

        if (bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
            return "UTF-8";
        } else if (bytes[0] == (byte) 0xFE && bytes[1] == (byte) 0xFF) {
            return "UTF-16BE";
        } else if (bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xFE) {
            if (bytes[2] == (byte) 0x00 && bytes[3] == (byte) 0x00) {
                return "UTF-32LE";
            } else {
                return "UTF-16LE";
            }
        } else {
            // 如果没有找到BOM或者不支持BOM的编码，可能需要更复杂的逻辑来检测或默认返回某种编码
            return "GBK"; // 默认猜测为GBK，这取决于你的应用场景
        }
    }
}
